package org.iks.common.aop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.iks.common.aop.TrackLogging;
import org.iks.common.util.StopWatchUtil;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * Author kzou
 * Date 2024/5/25
 * Description: 链路日志记录 {@link TrackLogging}
 */
@Slf4j
@Aspect
@Component
public class TrackLoggingAspect {

    @Pointcut("@annotation(org.iks.common.aop.TrackLogging)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        String trackName = null;
        if (signature instanceof MethodSignature methodSignature) {
            TrackLogging trackLogging = AnnotationUtils.findAnnotation(methodSignature.getMethod(), TrackLogging.class);
            if (trackLogging != null) {
                trackName = trackLogging.name();
            }
        }
        if (trackName == null) {
            return joinPoint.proceed(args);
        }
        StopWatch stopWatch = StopWatchUtil.stopWatch();
        if (stopWatch.isRunning()) {
            stopWatch.stop();
        }
        stopWatch.start(trackName);
        try {
            return joinPoint.proceed(args);
        }finally {
            stopWatch.stop();
        }
    }

}
